package com.dlc.beijingrfid.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dlc.commonlibrary.dialog.ActionSheetDialog;
import com.dlc.commonlibrary.utils.compress.CompressHelper;
import com.dlc.commonlibrary.utils.glide.GlideUtil;
import com.dlc.commonlibrary.widget.TitleBar;
import com.dlc.commonlibrary.widget.photoSelect.DialogManger;
import com.dlc.beijingrfid.R;
import com.dlc.beijingrfid.base.BaseActivity;
import com.dlc.beijingrfid.base.BaseApplication;
import com.dlc.beijingrfid.helper.UserHelper;
import com.dlc.beijingrfid.net.bean.LoginBean;
import com.dlc.beijingrfid.net.exception.ErrorMsgException;
import com.dlc.beijingrfid.net.protocol.UserProto;
import com.dlc.beijingrfid.net.protocol.base.HttpProtocol;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

import static com.dlc.beijingrfid.R.id.head_setting;

/**
 * Created by Administrator on 2017/7/18 0018.
 */

public class SettingActivity extends BaseActivity {
    @BindView(R.id.change_nickname)
    LinearLayout change_nickname;
    @BindView(head_setting)
    LinearLayout headSetting;
    @BindView(R.id.nickname)
    TextView nickname;
    @BindView(R.id.titleBar)
    TitleBar titleBar;
    @BindView(R.id.head)
    ImageView head_image;
    public final static int IMAGE_PICKER = 1000;
    public final static int TAKE_PHONE = 1001;
    @BindView(R.id.btn_exit)
    Button btnExit;
    private String selectPicPath = null;
    private boolean isChangeInfo = false;
    private boolean isUpdated = false;
    String nicknameStr;
    String avatar;

    @Override
    protected int getLayoutID() {
        return R.layout.activity_setting;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        titleBar.leftExit(this);
        Bundle bundle = getIntent().getExtras();
        String avatarStr = bundle.getString("avatar");
        String nicknameStr = bundle.getString("nickname");
        nickname.setText(nicknameStr);
        if (!TextUtils.isEmpty(avatarStr)) {
            GlideUtil.loadCircleImg(getActivity(), avatarStr,
                    head_image);
        } else {
            head_image.setImageDrawable(getResources().getDrawable(R.mipmap.ic_launcher_round));
        }

        change_nickname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(SettingActivity.this, ChangeNicknameActivity.class), 0);
            }
        });
        headSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ActionSheetDialog sheetDialog = ActionSheetDialog.newBuilder(getActivity()).addItem("照相").addItem("从相册选择").setOnSheetItemClickListener(new ActionSheetDialog.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {
                        switch (which) {
                            case 0:
                                Toast.makeText(SettingActivity.this, "照相", Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(SettingActivity.this, ImageGridActivity.class);
                                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                                startActivityForResult(intent, TAKE_PHONE);
                                break;
                            case 1:
                                Toast.makeText(SettingActivity.this, "从相册选择", Toast.LENGTH_SHORT).show();
                                Intent intent1 = new Intent(SettingActivity.this, ImageGridActivity.class);
                                startActivityForResult(intent1, IMAGE_PICKER);
                                break;
                        }
                    }
                }).build();

                sheetDialog.show();
            }
        });

        btnExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                BaseApplication.moveActivity(new LoginActivity());
                BaseApplication.exitApp();
                startActivity(new Intent(SettingActivity.this, LoginActivity.class));
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 2 && data != null) {
            nicknameStr = data.getStringExtra("nickname");
            nickname.setText(data.getStringExtra("nickname"));
        }
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == IMAGE_PICKER) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(
                        ImagePicker.EXTRA_RESULT_ITEMS);
                selectPicPath = images.get(0).path;
                processImage(images.get(0).path);
            } else if (data != null && requestCode == TAKE_PHONE) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(
                        ImagePicker.EXTRA_RESULT_ITEMS);
                selectPicPath = images.get(0).path;
                processImage(images.get(0).path);
            } else {
                Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
            }

            head_image.post(new Runnable() {
                @Override
                public void run() {
                    if (!TextUtils.isEmpty(selectPicPath)) {
                        File filePic = new File(selectPicPath);
                        uploadPic(filePic);
                        GlideUtil.loadCircleImg(SettingActivity.this, filePic,
                                head_image);

                    }
                }
            });
        }
    }

    /**
     * 处理图片
     *
     * @param path
     */
    private void processImage(final String path) {
        final DialogManger dialogManger = new DialogManger(getActivity(), DialogManger.DIALOG_TYPE_1,
                DialogManger.DIALOG_TYPE_1_PROCESSING);
        Observable.just(path)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        dialogManger.showDlg();
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .map(new Func1<String, String>() {
                    @Override
                    public String call(String s) {
                        File newFile = CompressHelper.getDefault(getActivity())
                                .compressToFile(new File(s));
                        return newFile.getAbsolutePath();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        dialogManger.dismissDlg();
                        selectPicPath = s;
                        isChangeInfo = true;

                    }
                });
    }

    private void uploadPic(File file) {
        showLoadingDialog();
        UserProto.get().alterHead(file, new HttpProtocol.Callback<LoginBean>() {
            @Override
            public void onSuccess(LoginBean loginBean) {
                dismissLoadingDialog();
                showToast(loginBean.msg);
                UserHelper.get().saveAvatar(loginBean.data.avatar);
                avatar = loginBean.data.avatar;
                Log.d("头像上传成功url---->", avatar);


            }

            @Override
            public void onFailed(int code, ErrorMsgException e) {
                dismissLoadingDialog();
                showToast(e.getMessage());
            }
        });
    }
/*
    @Override
    protected void onResume() {
        super.onResume();
        onRestart();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        GlideUtil.loadCircleImg(getActivity(), UserHelper.get().getAvatar(),
                head_image);

    }*/


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            intent.putExtra("avatar", avatar);
            intent.putExtra("nickname", nicknameStr);
            Log.d("头像回调url---->", "" + avatar);
            setResult(1, intent);
            finish();
        }
        return true;
    }
}
